package com.primestone.cim.batch;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.ejb.AccessTimeout;
import javax.ejb.Schedule;
import javax.ejb.Singleton;
import javax.ejb.Timer;

import com.primestone.cim.util.CIMFTPClient;
import com.primestone.cim.util.CompressUtil;
import com.primestone.cim.util.StringUtil;

/**
 * @author cesar.mateus
 * Oct 29, 2013 10:01:49 PM
 * TransferTimer.java
 * GetMeterReadingsClient
 * 
 */
@Singleton
public class TransferTimer {
	
	private final static Logger LOGGER = Logger.getLogger(TransferTimer.class.getName());
	
	private static CIMFTPClient ftpClient = null;
	
	static {
		try {
			ftpClient = new CIMFTPClient(
					CIMGMRProperties.FTP_HOST_PROP, CIMGMRProperties.FTP_PORT_PROP, CIMGMRProperties.FTP_USER_PROP, CIMGMRProperties.FTP_PWD_PROP);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

    /**
     * Default constructor. 
     */
    public TransferTimer() {}
	
	@SuppressWarnings("unused")
	@AccessTimeout(value=1, unit=TimeUnit.DAYS)
	@Schedule(minute="*/30", hour="*", 
			dayOfWeek="*", dayOfMonth="*", month="*", year="*", info="TransferTimer", persistent=false)
	private void scheduledTimeout(final Timer t) {
		LOGGER.log(Level.INFO, "@Schedule TransferTimer called at: {0}", new Date());

		if (CIMGMRProperties.TRANSFER_PROP ) {
			try {
				File dir = new File(CIMGMRProperties.TMP_DIR_PROP);
				File[] files = dir.listFiles(new FilenameFilter() {
					@Override
					public boolean accept(File dir, String name) {
						return name.toLowerCase().startsWith(StringUtil.PREFIX_BATCH_FILES) && name.toLowerCase().endsWith(StringUtil.SUFFIX_BATCH_FILES);
					}
				});

				int numFiles = files.length;

				File zippedFile;
				File obsoleteZippedFile;
				int i = 1;
				List<File> filesToDelete = new ArrayList<File>();
				LOGGER.log(Level.INFO, "---- *** begin Transfer of {0} files: {1}", new Object[]{numFiles, new Date()});
				for (File file : files) {
					LOGGER.log(Level.FINE, "---- file {0}: {1} of {2}.", new Object[]{file.getAbsolutePath(), i, numFiles});

					try {
						zippedFile = new File(new StringBuilder(file.getAbsolutePath()).append(StringUtil.SUFFIX_ZIPPED_BATCH_FILES).toString());
						CompressUtil.zipFile(zippedFile, file);
						ftpClient.uploadFile(zippedFile.getAbsolutePath(), zippedFile.getName(), CIMGMRProperties.FTP_DIR_PROP);
						obsoleteZippedFile = new File(zippedFile.getAbsoluteFile().toString().replace(StringUtil.PREFIX_BATCH_FILES, StringUtil.PREFIX_OLD_BATCH_FILES));
						zippedFile.renameTo(obsoleteZippedFile);
						filesToDelete.add(file);
					} catch (IOException e) {
						LOGGER.log(Level.WARNING, "---- IO Exception, file {0}: {1}", new Object[]{file.getAbsolutePath(), e.getMessage()});
						e.printStackTrace();
					} catch (Exception e) {
						LOGGER.log(Level.WARNING, "---- General Exception, file {0}: {1}", new Object[]{file.getAbsolutePath(), e.getMessage()});
					}

					i++;
				}
				LOGGER.log(Level.INFO, "---- *** end Transfer of {0} files: {1}", new Object[]{numFiles, new Date()});

				for (File file : filesToDelete) {
					file.delete();
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}